import styles from "@/styles/Test.module.css";
import { useEffect, useState } from "react";
import { Button, Progress, Table, message } from "antd";
import type { TableColumnsType } from "antd";
import { TableRowSelection } from "antd/es/table/interface";

type Dataset = {
  id: number;
  name: string;
  origin: string;
  createdAt: string;
  light: number;
  fog: number;
  noise: number;
  geo: number;
  scale: number;
};

const columns: TableColumnsType<Dataset> = [
  {
    title: "序号",
    dataIndex: "index",
    key: "index",
    align: "center",
    width: 80,
    render: (_text, _record, index) => `${index + 1}`,
  },
  {
    title: "名称",
    dataIndex: "name",
    key: "name",
    align: "center",
    width: 300,
  },
  {
    title: "光照",
    dataIndex: "light",
    key: "light",
    align: "center",
  },
  {
    title: "云雾",
    dataIndex: "fog",
    key: "fog",
    align: "center",
  },
  {
    title: "噪声",
    dataIndex: "noise",
    key: "noise",
    align: "center",
  },
  {
    title: "几何畸变",
    dataIndex: "geo",
    key: "geo",
    align: "center",
  },
  {
    title: "尺度变换",
    dataIndex: "scale",
    key: "scale",
    align: "center",
  },
];

export default function Test() {
  const [records, setRecords] = useState<Dataset[]>([]);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [progress, setProgress] = useState<number>(0);

  useEffect(() => {
    (async () => {
      const res = await fetch("http://localhost:3000/dataset");
      const data = await res.json();
      setRecords(data);
    })();
  }, []);

  const [selectedRows, setSeletedRows] = useState<Dataset[]>([]);

  const rowSelection: TableRowSelection<Dataset> = {
    onChange: (_keys, rows) => {
      setSeletedRows(rows);
    },
  };

  async function runAlgorithm() {
    setProgress(0);
    setIsLoading(true);
    const source = new EventSource(
      `http://localhost:3000/test/run/${selectedRows[0].id}`
    );
    source.addEventListener("message", (event) => {
      setProgress(event.data);
    });
    source.addEventListener("result", (event) => {
      const [indicator1, indicator2] = event.data.split(" ");
      message.success(
        `测试结束，指标mAP0.5为${indicator1}，指标mAP50_95为${indicator2}`,
        10
      );
      setIsLoading(false);
      source.close();
    });
  }

  return (
    <>
      <div className={styles.toolBar}>
        <Button
          type="primary"
          disabled={selectedRows.length === 0}
          loading={isLoading}
          onClick={runAlgorithm}
        >
          测试
        </Button>
        <Progress percent={progress} style={{ width: "600px" }}></Progress>
      </div>
      <Table
        rowSelection={rowSelection}
        rowKey={(record) => record.id}
        columns={columns}
        dataSource={records}
        bordered
        scroll={{ y: 680 }}
      />
    </>
  );
}
